import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Spin, Button, Input, Col, Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import DescriptionList from '@/components/DescriptionList';
import StaticTable from './staticTable';

const { Description } = DescriptionList;
const FormItem = Form.Item;
@Form.create()
@connect(({ loading, payapply }) => ({
  loading: loading.models.payapply,
  detailData: payapply.detailData,
  payapply,
}))
class Detail extends Component {
  state = {
    type: '',
    paymentId: '',
  };

  tableSearchLayout = {
    labelCol: { xl: { span: 6 }, xxl: { span: 7 } },
    wrapperCol: { xl: { span: 18 }, xxl: { span: 17 } },
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { paymentId } = queryString.parse(location.search);

    dispatch({
      type: 'payapply/getFmPay',
      payload: { paymentId },
    }).then(data => {
      console.log(data, 'data');
      if (!data) return;
      this.setState({ payapplytype: data.bizType });
      dispatch({
        type: 'payapply/initialPageData',
        payload: data.bizType,
      });
      // 获取详情页业务数据
      dispatch({
        type: 'payapply/handleBusiData',
        payload: {
          bizType: data.bizType,
          data,
          feeType: data.feeType,
        },
      });
      let type = '';
      if (location.pathname === '/fmmanage/payapply/canclefmpay') {
        type = 'cancel';
      } else {
        type = 'detail';
      }
      this.setState({
        type,
        paymentId,
      });
    });
  }

  // 保存
  save = () => {
    const { form, dispatch } = this.props;
    const { paymentId } = this.state;
    form.validateFields(['canclRsn'], (err, values) => {
      if (err) return;
      Modal.confirm({
        title: <div>确认取消支付申请吗？</div>,
        icon: <ExclamationCircleOutlined />,
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          dispatch({
            type: 'payapply/cancleFmPay',
            payload: {
              ...values,
              paymentId,
            },
          });
        },
        onCancel() {},
      });
    });
  };

  // 获取表格columns
  columnsRender = data => {
    if (!data) return [];
    return data.map((item, i) => ({
      title: item.label,
      dataIndex: item.prop,
      onCell: () => ({ style: { textAlign: item.cellTextAlign || 'left' } }),
      onHeaderCell: () => ({
        style: { fontWeight: 'bold', textAlign: item.headerTextAlign || 'left' },
      }),
      render: text => {
        switch (item.type) {
          case 'date':
            return moment(text).format('YYYY-MM-DD HH:mm');
          case 'dateYm':
            return moment(text).format('YYYY-MM');
          default:
            return text || '--';
        }
      },
      key: item.prop + i,
    }));
  };

  // 切换取到的值
  getSwitchData = () => {
    const {
      payapply: {
        payApplySubmitData: { firstStep },
        switchColumnsList,
      },
      detailData,
    } = this.props;
    const { payapplytype } = this.state;
    if (!payapplytype || !switchColumnsList.columns) return null;
    // 单选情况中，只有值为2和4为切换之后的值
    if (+detailData.feeType === 2 || +detailData.feeType === 4) {
      return switchColumnsList.columns[`columns${payapplytype}`];
    }
    return firstStep.columns;
  };

  render() {
    const {
      loading,
      detailData,
      form: { getFieldDecorator },
      payapply: {
        payApplySubmitData: { firstStep },
        switchColumnsList,
        businessData,
      },
    } = this.props;
    const { type, payapplytype } = this.state;
    const columns = this.columnsRender(this.getSwitchData());
    const formItemLayout = {
      labelCol: {
        md: {
          span: 3,
        },
      },
      wrapperCol: {
        md: {
          span: 18,
        },
      },
    };
    let rowKey;
    if (!payapplytype || !switchColumnsList.rowKey) {
      rowKey = '';
    } else {
      rowKey =
        detailData.feeType && (+detailData.feeType === 2 || +detailData.feeType === 4)
          ? switchColumnsList.rowKey[`rowKey${payapplytype}`]
          : firstStep.rowKey;
    }
    return (
      <Spin spinning={loading} delay={0}>
        <div>
          <PageHeaderWrapper>
            {type === 'detail' && (
              <Card
                title={
                  <span style={{ fontWeight: 'bolder' }} id="sendInfor">
                    支付申请信息
                  </span>
                }
                bordered={false}
              >
                <DescriptionList>
                  <Description term="申请人">
                    {detailData.aplctName ? detailData.aplctName : '--'}
                  </Description>
                  <Description term="支付用途">
                    {detailData.feeTypeName ? detailData.feeTypeName : '--'}
                  </Description>
                  <Description term="支付金额(元)">
                    {detailData.actualAmount ? detailData.actualAmount : '--'}
                  </Description>
                  <Description term="支付状态">
                    {detailData.payStateName ? detailData.payStateName : '--'}
                  </Description>

                  <Description term="申请时间">
                    {detailData.applTime
                      ? moment(detailData.applTime).format('YYYY-MM-DD HH:mm')
                      : '--'}
                  </Description>
                  <Description term="签收时间">
                    {detailData.signTime
                      ? moment(detailData.signTime).format('YYYY-MM-DD HH:mm')
                      : '--'}
                  </Description>
                  {/* 取消状态下显示取消原因和取消时间 */}
                  {+detailData.payState === 4 && (
                    <Description term="取消原因">
                      {detailData.canclRsn ? detailData.canclRsn : '--'}
                    </Description>
                  )}
                  {+detailData.payState === 4 && (
                    <Description term="取消时间">
                      {detailData.canclTime
                        ? moment(detailData.canclTime).format('YYYY-MM-DD HH:mm')
                        : '--'}
                    </Description>
                  )}
                </DescriptionList>
              </Card>
            )}
            <Card
              title={
                <span style={{ fontWeight: 'bolder' }} id="sendInfor">
                  业务数据
                </span>
              }
              bordered={false}
            >
              <StaticTable
                payapplytype={payapplytype}
                businessData={businessData}
                rowKey={rowKey}
                columns={columns}
              />
            </Card>
            <Card
              title={
                <span style={{ fontWeight: 'bolder' }} id="sendInfor">
                  收款人信息
                </span>
              }
              bordered={false}
            >
              <DescriptionList>
                <Description term="收款人类型">
                  {detailData.payeeTypeName ? detailData.payeeTypeName : '--'}
                </Description>
                <Description term="收款人名称">
                  {detailData.payee ? detailData.payee : '--'}
                </Description>
                <Description term="收款银行">
                  {detailData.bankCodeName ? detailData.bankCodeName : '--'}
                </Description>
                <Description term="开户行">
                  {detailData.bankOfDepo ? detailData.bankOfDepo : '--'}
                </Description>
                <Description term="收款账号">
                  {detailData.account ? detailData.account : '--'}
                </Description>
                {type === 'cancel' && (
                  <Description term="支付金额(元)">
                    {detailData.actualAmount ? detailData.actualAmount : '--'}
                  </Description>
                )}
              </DescriptionList>
            </Card>
            {type === 'cancel' && (
              <Card
                title={
                  <span style={{ fontWeight: 'bolder' }} id="sendInfor">
                    取消
                  </span>
                }
                bordered={false}
              >
                <Form>
                  <Col span={16}>
                    <FormItem label="取消原因" {...formItemLayout}>
                      {getFieldDecorator('canclRsn', {
                        rules: [
                          {
                            required: true,
                            message: '请输入取消原因',
                          },
                          {
                            max: 100,
                            message: '最多输入100字符',
                          },
                        ],
                      })(
                        <Input.TextArea placeholder="请输入" rows={4} style={{ width: '100%' }} />
                      )}
                    </FormItem>
                  </Col>
                </Form>
              </Card>
            )}

            <FooterToolbar style={{ width: '100%' }}>
              <Button
                onClick={() => {
                  router.goBack();
                }}
              >
                返回
              </Button>
              {type === 'cancel' && (
                <Button style={{ marginLeft: 16 }} type="primary" onClick={() => this.save()}>
                  提交
                </Button>
              )}
            </FooterToolbar>
          </PageHeaderWrapper>
        </div>
      </Spin>
    );
  }
}

export default Detail;
